<template>
  <div class="header">
      <div class="logo" @click="goPage('/index')">
          MeClan
      </div>
          <el-dropdown class="user" v-if="isLogin == 0">
    <span class="el-dropdown-link">
      登录 / 注册
      <el-icon class="el-icon--right">
        <arrow-down />
      </el-icon>
    </span>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item @click="goPage('/login')"> 登 录 </el-dropdown-item>
        <el-dropdown-item @click="goPage('/register')"> 注 册 </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
  <el-dropdown class="user" v-else>
    <span class="el-dropdown-link">
      <div class="user-info">
          <span>{{user.nickname}}</span>
          <img :src="user.avatar" alt="">
      </div>
      <el-icon class="el-icon--right">
        <arrow-down />
      </el-icon>
    </span>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item @click="goPage('/user')"> 用户中心 </el-dropdown-item>
        <el-dropdown-item @click="logout"> 退出登录 </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
  </div>
</template>

<script>
import { ArrowDown } from '@element-plus/icons'
import { reactive, toRefs } from '@vue/reactivity'
import { onMounted } from '@vue/runtime-core'
import { useRouter } from 'vue-router'
import {Success} from "../utils/notify";
import {useStore} from "vuex";
export default {
    name:'HeaderBar',
    components:{ArrowDown},
    setup(){
        const router = useRouter()
        const store = useStore();
        const state = reactive({
            isLogin : localStorage.getItem('isLogin') || 0,
            user    : {}
        })
        const methods = {
          logout(){
            localStorage.removeItem('user-token')
            localStorage.removeItem('user-info')
            sessionStorage.removeItem('user-info')
            localStorage.setItem('isLogin',0)
            state.isLogin = 0
            Success('成功退出登录！')
            setTimeout(function () {
              router.push('/')
            },1500)
          },
          goPage(url){
            router.push(url)
          }
        }
        onMounted(()=>{
          if(state.isLogin == 1){
            state.user = JSON.parse(localStorage.getItem('user-info'))
            state.isLogin = 1
          }

        })
        return {
            ...toRefs(state),
            ...methods
        }
    }
}
</script>

<style scoped>
.logo{
  cursor: pointer;
}
</style>